<template>
  <div>
      <template v-if="$attrs.UploadType == 'img' || $attrs.UploadType == '图片'">
          <avatar-html
            v-if="$attrs.limit == 1 && $attrs.UploadType == 'spec'"
            :value="fieldValue"
            :imageUrl="imageUrl"
            v-bind="$attrs"
            v-on="$listeners"
            @handlePictureCardPreview="handlePictureCardPreview"
            @handleRemove="handleRemove"
            @handProgress="handProgress"
            ></avatar-html>


            <thumb-html
            v-else-if="
                $attrs.limit == 1 &&
                $attrs.UploadType != 'spec'
                "
            :value="fieldValue"
            :imageUrl="imageUrl"
            v-bind="$attrs"
            v-on="$listeners"
            @handlePictureCardPreview="handlePictureCardPreview"
            @handleRemove="handleRemove"
            @handProgress="handProgress"
            @checkInput="checkInput"
            @selectPicture="selectPicture"
            ></thumb-html>


            <images-html
            v-else-if="
                $attrs.limit > 1
            "
            :value="fieldValue"
            :imageUrl="imageUrl"
            v-bind="$attrs"
            v-on="$listeners"
            @handlePictureCardPreview="handlePictureCardPreview"
            @handleRemove="handleRemove"
            @handProgress="handProgress"
            @checkInput="checkInput"
            @selectPicture="selectPicture"
            ></images-html>

            
      </template>
       
      <template v-else-if="$attrs.UploadType == 'video'">
          <video-html v-if="$attrs.limit == 1" 
            :value="fieldValue"
            :imageUrl="imageUrl"
            :percentage="percentage"
            v-bind="$attrs"
            v-on="$listeners"
            @handlePictureCardPreview="handlePictureCardPreview"
            @handleRemove="handleRemove"
            @handProgress="handProgress"
            @checkInput="checkInput"
            @selectPicture="selectPicture">
            
            </video-html>
      </template>
      <template v-else-if="$attrs.UploadType == 'file'">
          <file-html  
            :value="fieldValue"
            :imageUrl="imageUrl"
            v-bind="$attrs"
            v-on="$listeners"
            @handlePictureCardPreview="handlePictureCardPreview"
            @handleRemove="handleRemove"
            @handProgress="handProgress"
            @checkInput="checkInput"
            @selectPicture="selectPicture"></file-html>
      </template>

    <el-dialog :visible.sync="dialogVisible">
      <el-carousel
        v-if="dialogVisible"
        :initial-index="imgInx"
        arrow="always"
        :autoplay="false"
        style="height: 400px"
      >
        <el-carousel-item
          v-for="item in imageUrl"
          :key="item.uid"
          style="height: 400px"
        >
          <img style="width: 100%; height: 100%" :src="item.url" alt="" />
        </el-carousel-item>
      </el-carousel>
    </el-dialog>

    <el-dialog :visible.sync="dialogFormVisible"   append-to-body title="请输入网络地址提交数据">
        <el-form ref="formDatas" :model="formDatas" label-width="120px">
            <el-form-item label="网络图片地址">
                <el-input v-model="formDatas.imagePath"></el-input>
            </el-form-item>
            <el-form-item >
                <div style="text-align:right;margin-top:30px;">
                    <el-button type="primary" @click="onSubmit">确 定</el-button>
                    <el-button @click="function(){return dialogFormVisible=false;}">取 消</el-button>
                </div>
            </el-form-item>
        </el-form>
    </el-dialog>

    <el-dialog :visible.sync="dialogPictureVisible"  append-to-body width="1008px" title="请选择需要的图片">
        <picture-html @checkPicture="checkPicture" @cancelPicture="function(){return dialogPictureVisible=false;} " :limits="$attrs.limit" :isPrivate="isPrivate"></picture-html>
    </el-dialog>
  </div>
</template>

<script>
import * as qiniu from "qiniu-js";
import Md5 from "crypto-js/md5.js";
import {
  getQiNiuToken,
  getQiNiuImagePath,
  getPrivateImagePath,
} from "@/api/common";
export default {
  components: {
    avatarHtml: () => import("./src/avatar.vue"),
    thumbHtml: () => import("./src/thumb.vue"),
    imagesHtml: () => import("./src/images.vue"),
    pictureHtml: () => import("./src/picture.vue"),
    videoHtml: () => import("./src/video.vue"),
    fileHtml: () => import("./src/file.vue"),
  },
  props: {
    value: {
      type: [String, Number],
      default() {
        return "";
      },
    },
    uploadText: {
      type: String,
      default: "点击上传",
    },
    selectText: {
      type: String,
      default: "选取文件",
    },
    submitText: {
      type: String,
      default: "上传到服务器",
    },
    tipText: {
      type: String,
      default: "只能上传jpg/png文件，且不超过500kb",
    },
    size: {
      type: String,
    },
  },
  data() {
    return {
      accept: "",
      imageUrl: [],
      img: "",
      imagePath: "",
      coverId: "",
      dialogVisible: false,
      isPrivate: this.$attrs.isPrivate,
      percentage: 0,
      imgInx: 0,
      dialogFormVisible:false,
      dialogPictureVisible:false,
      formDatas:{
          imagePath:''
      }
    };
  },
  computed: {
    fieldValue: {
      get() {
        this.coverId = this.value ? String(this.value) : "";
        if (this.value) {
          this.getImageUrl();
        } else {
          this.imageUrl = [];
          this.imagePath = "";
        }

        // console.log(this.$attrs,this.value,this.$route,'-uplode-------------')
        //   return this.coverId;
        return this.imagePath;
      },
      set(val) {
        // this.$emit('input', val)
      },
    },
  },
  methods: {
    //选择图库图片
    selectPicture() {
        this.dialogPictureVisible = true;
    },
    checkPicture(obj){
         if(this.$attrs.limit > 1 && this.$attrs.limit <= this.imageUrl.length) {
            this.$message({
                message: '最大只能上传'+this.$attrs.limit+'张!',
                type: 'error'
            });
            return false;
        }

        for(var i in obj) {
          var url = obj[i].url ? obj[i].url + '/' : '';
          var res = {
              data:{
                  cover_id:obj[i].id,
                  path:url + obj[i].path,
                  url:obj[i].src_text,
                  name:obj[i].name,
              }
          }
          this.assemblingParam(res,obj[i].name);
        }
        
         this.dialogPictureVisible = false;
    },
    //查看图片
    handlePictureCardPreview(file) {
      var that = this;
      this.imageUrl.forEach((item, inx) => {
        if (item.name == file.name) {
          that.imgInx = inx;
        }
      });
      this.dialogVisible = true;
    },
    //删除图片
    handleRemove(file, fileList) {
      let newPath = [];
      let newCoverId = [];

      for (var i in fileList) {
        newPath.push(fileList[i].path);
        newCoverId.push(fileList[i].cover_id);
      }

      this.imagePath = newPath.join(",");
      this.coverId = newCoverId.join(",");

      this.imageUrl = fileList;

      this.$emit("input", this.coverId);
    },
    //上传七牛
    handProgress(file, fileList) {
      let that = this;
      this.getToken(file, function (res, state) {
        if (!state) {
          return false;
        }

        that.token = res.token;
        that.hostUrl = res.hostUrl;

        let key = Md5(new Date().getTime()).toString() + file.name;
        let token = res.token;
        let putExtra = {};
        let config = {
          useCdnDomain: true,
          disableStatisticsReport: false,
          retryCount: 6,
          region: qiniu.region.z2,
        };

        const observable = qiniu.upload(file.raw, key, token, putExtra, config);

        const subscription = observable.subscribe({
          next: function (res) {
            if (res.total.percent == 100) {
              that.percentage = 0;
            } else {
              that.percentage = res.total.percent;
            }
          },
          error: function (res) {
            console.log(res);
          },
          complete: function (res) {
            var fileArr = {
              img_path: that.hostUrl + "/" + res.key,
              name: file.raw.name,
              is_private: that.$attrs.isPrivate,
              path: res.key,
              hash: res.hash,
              host: that.hostUrl,
              type: file.raw.flag,
              size: file.raw.size,
              route: that.$route.path,
            };
            that.percentage = 0;
            that.getImagePath(fileArr);
          },
        });
      });
    },
    //获得七牛token
    async getToken(file, callback) {
      let params = {
        filename: file.name,
        type: file.raw.type,
        size: file.raw.size,
        is_private: this.$attrs.isPrivate,
      };
      const res = await getQiNiuToken(params);
      if (res.code == 200) {
        return callback(res.data, true);
      }

      this.assemblingParam(res);
      return callback(res.data, false);
    },
    //上传服务器
    getImagePath: async function (obj) {
      const res = await getQiNiuImagePath(obj);
      if (res.code == 200) {
        this.assemblingParam(res, obj.name);
      }
    },
    //组装图片参数
    assemblingParam(res, filename) {
      if (this.$attrs.limit == 1) {
        this.imagePath = res.data.path;
        this.coverId = res.data.cover_id;
        this.imageUrl[0] = res.data;
        // this.$refs.upload.clearFiles();
      } else {
        var newPath = this.imagePath ? this.imagePath.split(",") : [];
        var newCoverId = this.coverId ? this.coverId.split(",") : [];

        newPath.push(res.data.path);

        newCoverId.push(res.data.cover_id);

        this.imagePath = newPath.join(",");

        this.coverId = newCoverId.join(",");

        if (filename) {
          res.data.name = filename;
        }
      }

      this.imageUrl.push(res.data);
      
      this.$emit("input", this.coverId);
    },
    checkInput(){
        this.dialogFormVisible = true;
    },
    onSubmit(){
        if(!this.formDatas.imagePath) {
            this.$message({
                message: '请先输入网络地址!',
                type: 'error'
            });
            return false;
        }
        if(this.$attrs.limit > 1 && this.$attrs.limit <= this.imageUrl.length) {
            this.$message({
                message: '最大只能上传'+this.$attrs.limit+'张!',
                type: 'error'
            });
            return false;
        }
        var obj = {
            img_path:this.formDatas.imagePath,
            path:this.formDatas.imagePath,
            name:Md5(this.formDatas.imagePath).toString(),
            type:1,
            is_private:0
        };
        this.getImagePath(obj);
        this.formDatas.imagePath = '';
        this.dialogFormVisible = false;
    },
    //图片ID转图片地址
    async getImageUrl() {
      var ids = this.coverId.split(",");
      const res = await getPrivateImagePath({ ids: ids });
      if (res.code == 200) {
        this.imageUrl = [];
        this.imagePath = res.data.path.join(",");
        res.data.url.forEach((item, inx) => {
          var arr = res.data.path[inx].split("/");
          var obj = {
            url: item,
            path: res.data.path[inx],
            cover_id: res.data.cover_id[inx],
            name: arr[arr.length - 1],
          };
          this.imageUrl.push(obj);
        });
      }
    },
  },
};
</script>